package com.supor.aiot.mine.ui.wechat;


import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.net.Uri;
import android.os.Environment;
import android.view.View;
import android.widget.LinearLayout;

import com.android.baseconfig.base.GlideApp;
import com.android.baseconfig.common.rxpermissions2.RxPermissions;
import com.android.baseconfig.common.utils.FileUtil;
import com.android.baseconfig.common.utils.Logc;
import com.android.baseconfig.common.utils.ToastUtils;
import com.android.baseconfig.common.views.AppBasicDialog;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.base.BaseMVVMActivity;
import com.supor.aiot.common.entity.Result;
import com.supor.aiot.common.helper.ActivityHelper;
import com.supor.aiot.mine.R;
import com.supor.aiot.mine.databinding.ActivityWechatStartBinding;

import java.io.File;
import java.io.FileOutputStream;

public class WechatStartActivity extends BaseMVVMActivity<WechatViewModel, ActivityWechatStartBinding> {

    private RxPermissions rxPermissions;
    private AppBasicDialog commonDialog;

    @Override
    protected int resourceId() {
        return R.layout.activity_wechat_start;
    }

    @Override
    protected void initView() {
        super.initView();
        bindingView.setViewM(this);
        bindingView.toolbar.setIvLeftOnClickListener(v -> finish());
        bindingView.toolbar.setTvLeftOnClickListener(v -> finish());

        bindingView.btnSavePhoto.setOnClickListener(v -> {
            showLoading();
            checkPermission();
        });
    }

    @Override
    protected void initData() {
        super.initData();
        rxPermissions = new RxPermissions(this);
        showLoading();
        viewModel.setWechatOauth("yes");
        viewModel.getOauthResult().observe(this, result -> {
            closeLoading();
            if (result instanceof Result.Success) {
                String data = (String) result.getData();
                if (data != null && data.length() > 6) {
                    GlideApp.with(this)
                            .load(data)
                            .into(bindingView.ivQrCode);
                }
            } else if (result instanceof Result.Error) {
                ToastUtils.getInstance().showCustomToast("获取微信二维码失败: " + ((Result.Error) result).getErrorMsg());
                bindingView.btnSavePhoto.setVisibility(View.GONE);
            }
        });
    }


    @SuppressLint({"CheckResult", "AutoDispose"})
    private void checkPermission() {
        rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(aboolean -> {
                    if (aboolean) {
                        savePhoto();
                    } else {
                        Logc.i("permission request: failed");
                        showFailedDialog();
                        closeLoading();
                    }
                }, throwable -> {
                    ToastUtils.getInstance().showCustomToast("出错啦" + throwable.getMessage());
                });
    }

    private void savePhoto() {
        try {
            Bitmap cacheBmp = viewConversionBitmap(bindingView.llMainContent);
            FileOutputStream fos;

            String filePath =
                    Environment.getExternalStorageDirectory() + "/Download/苏泊尔/苏泊尔App公众号.png";
            FileUtil.createDirs(Environment.getExternalStorageDirectory() + "/Download/苏泊尔");
            File photoFile = new File(filePath);
            fos = new FileOutputStream(photoFile);
            cacheBmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();

            // 更新系统相册
            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri uri = Uri.fromFile(photoFile);
            intent.setData(uri);
            sendBroadcast(intent);
            ToastUtils.getInstance().showCustomToast("已保存到系统相册");

            // 布局复原
            LinearLayout.LayoutParams layout = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            layout.setMargins(getResources().getDimensionPixelSize(R.dimen.dp_15),
                    getResources().getDimensionPixelSize(R.dimen.dp_68), getResources().getDimensionPixelSize(R.dimen.dp_15), 0);
            bindingView.llMainContent.setLayoutParams(layout);

        } catch (Exception e) {
            ToastUtils.getInstance().showCustomToast("保存失败，请重试");
            Logc.e("savePhoto failed :" + e.getMessage());
        }
        closeLoading();
    }

    /**
     * view转bitmap
     */
    private Bitmap viewConversionBitmap(View v) {

        if (v == null) return null;

        int w = v.getWidth();
        int h = v.getHeight();

        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bmp);

        c.drawColor(Color.WHITE);
        /** 如果不设置canvas画布为白色，则生成透明 */

        v.layout(0, 0, w, h);
        v.draw(c);

        return bmp;
    }

    protected void showFailedDialog() {
        if (commonDialog != null && commonDialog.isShowing()) {
            commonDialog.dismiss();
        }
        AppBasicDialog.Builder builder = new AppBasicDialog.Builder(this, false);
        builder.setTitle(R.string.permission_storage_title);
        builder.setMessage(R.string.permission_storage_msg);
        builder.setNegativeButton(R.string.cancel, (dialog, which) -> {
            dialog.dismiss();
        });
        builder.setPositiveButton(R.string.go_settings, (dialog, which) -> {
            ActivityHelper.startAppSettings(this, Constants.REQUEST_CODE);
            dialog.dismiss();
        });
        commonDialog = builder.create();
        commonDialog.setCancelable(false);
        commonDialog.show();
    }
}